<?php


namespace Xiaoguai\DesignPattern\DP013\Composite;


use Xiaoguai\DesignPattern\DP013\Component;

class Composite implements Component
{
    /**
     * @var Component[] $children
     */
    protected $children = [];

    public function add(Component $component): void
    {
        $this->children[] = $component;
    }

    public function remove(Component $component): void
    {
        $index = array_search($component, $this->children, true);
        if ($index !== false) {
            array_splice($this->children, $index, 1);
        }
    }

    public function getChild(int $depth): Component
    {
        return $this->children[$depth];
    }

    public function operation(): void
    {
        foreach ($this->children as $child) {
            $child->operation();
        }
    }

}